package com.etone.smartAudit.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.AccountInfo;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.Item;
import com.etone.smartAudit.domain.ItemSource;
import com.etone.smartAudit.dto.accountInfo.AccountInfoDTO;
import com.etone.smartAudit.enums.AccountType;
import com.etone.smartAudit.enums.StateType;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.AccountInfoMapper;
import com.etone.smartAudit.mapper.ItemSourceMapper;
import com.etone.smartAudit.mapstruct.AccountInfoMapstruct;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.accountInfo.AccountInfoVO;
import com.etone.smartAudit.vo.item.ItemExpansionSourceVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: sovy
 * @date: 2020/11/12
 * @description:
 */

@Service
@AllArgsConstructor
public class AccountInfoService extends ServiceImpl<AccountInfoMapper, AccountInfo> {

    private AdminPermissionService adminPermissionService;

    private AccountInfoMapstruct accountInfoMapstruct;

    private ItemSourceMapper itemSourceMapper;

    /**
     * 账号列表
     *
     * @param admin
     * @param serverId
     * @param serverName
     * @param serverIp
     * @param type
     * @param itemId
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<AccountInfoVO> list(Admin admin, Integer serverId, String serverName, String serverIp, AccountType type, Integer itemId, int page, int pageSize) {
        boolean hasPermission = admin.isAdmin() || adminPermissionService.hasPermission(admin, "show_all_account");
        Page<AccountInfoVO> accountInfoVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> baseMapper.findList(hasPermission ? null : admin.getId(), serverId, serverName, serverIp, type, itemId));

        return PagerVO.of(accountInfoVOPage);
    }

    /**
     * 账号信息详情
     *
     * @param id
     * @return
     */
    public AccountInfo get(Integer id) {
        AccountInfo accountInfo = getById(id);
        if (accountInfo != null) {
            return accountInfo;
        }
        throw new CustomParameterizedException("账号不存在");
    }

    /**
     * 获取账号详情
     *
     * @param serverId
     * @param itemId
     * @param accountType
     * @param isSupper    是否是超级管理员
     * @return
     */
    public AccountInfoVO get(Integer serverId, Integer itemId, AccountType accountType, Boolean isSupper) {
        AccountInfoVO accountInfo = baseMapper.findOne(serverId, itemId, accountType, isSupper);
        if (accountInfo == null) {
            throw new CustomParameterizedException("本项目无相关资源");
        }
        return accountInfo;
    }

    /**
     * 账号信息详情
     *
     * @param id
     * @return
     */
    public AccountInfoVO detail(Integer id) {
        AccountInfoVO accountInfoVO = baseMapper.findDetail(id);
        if (accountInfoVO == null) {
            throw new CustomParameterizedException("账号不存在");
        }
        return accountInfoVO;
    }

    /**
     * 增加|编辑账号
     *
     * @param admin
     * @param id
     * @param accountInfoDTO
     */
    public void save(Admin admin, Integer id, AccountInfoDTO accountInfoDTO) {
        AccountInfo accountInfo;
        if (id == null) {
            accountInfo = AccountInfo.builder().createAdminId(admin.getId()).createAdminName(admin.getNickName()).createTime(new Date()).build();
        } else {
            accountInfo = get(id);
        }
        accountInfoMapstruct.copy2AccountInfoDTO(accountInfo, accountInfoDTO);
        if (id == null) {
            baseMapper.insert(accountInfo);
        } else {
            LambdaUpdateWrapper<AccountInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(AccountInfo::getId, id);
            wrapper.set(AccountInfo::getPort, accountInfo.getPort());
            baseMapper.update(accountInfo, wrapper);
        }

    }

    /**
     * 增加账号
     *
     * @param admin
     * @param item
     * @param itemExpansionSources
     */
    public void add(Admin admin, Item item, List<ItemExpansionSourceVO> itemExpansionSources) {
        Date now = new Date();
        List<ItemSource> itemSources = itemSourceMapper.selectList(null);
        Map<Integer, ItemSource> itemSourceMap = itemSources.stream().collect(Collectors.toMap(ItemSource::getId, itemSource -> itemSource));
        List<AccountInfo> accountInfos = itemExpansionSources.stream().map(itemExpansionSourceVO -> {
            //资源
            ItemSource itemSource = itemSourceMap.get(itemExpansionSourceVO.getItemSourceId());

            //账号类型
            AccountType accountType = AccountType.parseFromItemSource(itemSource);

            AccountInfo accountInfo = AccountInfo
                    .builder()
                    .createAdminId(admin.getId())
                    .createAdminName(admin.getNickName())
                    .createTime(now)
                    .state(StateType.ENABLE)
                    .itemId(item.getId())
                    .itemName(item.getName())
                    //把type转成账号类型
                    .type(accountType)
                    .isSupper(false)
                    .build();
            accountInfoMapstruct.copy2AccountInfo(accountInfo, itemExpansionSourceVO);
            return accountInfo;
        }).collect(Collectors.toList());
        saveBatch(accountInfos);
    }

    /**
     * 删除账号
     *
     * @param id
     */
    public void delete(Integer id) {
        removeById(id);
    }
}
